package app.models.booking;

import com.github.sog.annotation.TableBind;
import com.github.sog.config.StringPool;
import com.github.sog.controller.datatables.core.ColumnDef;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author liuhui
 * @version 1.0 14-5-24 下午5:23
 */
@TableBind(tableName = "ol_ktv_project")
public class KtvProject extends Model<KtvProject> {
    public static final  KtvProject       dao              = new KtvProject();
    private static final org.slf4j.Logger logger           = LoggerFactory.getLogger(KtvProject.class);
    private static final long             serialVersionUID = -1502374007320765833L;

    public Page<KtvProject> datatable(DatatablesCriterias criterias, String name) {

        String where = SqlKit.sql("ktv.columns-where");
        List<Object> params = Lists.newArrayList();
        if (!Strings.isNullOrEmpty(name)) {
            where += (" WHERE name like ?");
            params.add("%" + name + "%");
        }
        int pageSize = criterias.getDisplaySize();
        int start = criterias.getDisplayStart() / pageSize + 1;
        final List<ColumnDef> sortingColumnDefs = criterias.getSortingColumnDefs();


        if (sortingColumnDefs != null && !sortingColumnDefs.isEmpty()) {
            StringBuilder orderBy = new StringBuilder();
            for (ColumnDef sortingColumnDef : sortingColumnDefs)
                if (sortingColumnDef.isSortable()) {
                    orderBy.append(sortingColumnDef.getName()).append(StringPool.SPACE).append(sortingColumnDef.getSortDirection().toString());
                }
            final String byColumns = orderBy.toString();
            if (!Strings.isNullOrEmpty(byColumns)) {
                where += " ORDER BY " + byColumns;
            }
        }
        if (!where.contains("ORDER")) {
            where += " ORDER BY order_id ASC";
        }


        return paginate(start, pageSize, SqlKit.sql("ktv.columns-select"), where, params.toArray());
    }

    public List<KtvProject> findByAll() {

        return find(SqlKit.sql("ktv.findByAll"), 1);
    }

    public KtvProject findByPk(long id) {
        return findFirst(SqlKit.sql("ktv.findByPk"), id);
    }
}
